﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace BWindingMachine
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        public string SetProductName
        {
            get
            {
                return txt_ProductName.Text;
            }
            set
            {
                txt_ProductName.Text = value;
            }
        }

        public string SetProductNumber
        {
            get
            {
                return txt_ProductNumber.Text;
            }
            set
            {
                txt_ProductNumber.Text = value;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Data.sp1.Close();
            Data.action();
            FormScreen.HideHHTaskBar();
        }
        
        private void btn_Exit_Click(object sender, EventArgs e)
        {
            DialogResult a = MessageBox.Show(" 是否关闭机器", "消息", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
            if (a == DialogResult.Yes)
            {
                Data.Send("Shutdown");
                System.Threading.Thread.Sleep(50);
                Data.Send("Shutdown");
                System.Threading.Thread.Sleep(50);
                Data.Send("Shutdown");
                System.Threading.Thread.Sleep(50);
                MessageBox.Show("机器正在关闭，请勿关闭电源！！！请在20秒后关闭机器电源。");

            }
        }

        private void btn_Step_Click(object sender, EventArgs e)
        {
            if (Data.DataOutput[40] == 1)
            {
                Data.Send("output#40#0#");

            }
            else
            {
                Data.Send("output#40#1#");

            }
        }

        private void btn_last_Click(object sender, EventArgs e)
        {
            if (Data.DataOutput[41] == 1)
            {
                Data.Send("output#41#0#");

            }
            else
            {
                Data.Send("output#41#1#");

            }
        }

        private void btn_1shineng_Click(object sender, EventArgs e)
        {
            if (Data.DataOutput[38] == 1)
            {
                Data.Send("output#38#0#");

            }
            else
            {
                Data.Send("output#38#1#");

            }
        }

        private void btn_2shineng_Click(object sender, EventArgs e)
        {
            if (Data.DataOutput[39] == 1)
            {
                Data.Send("output#39#0#");

            }
            else
            {
                Data.Send("output#39#1#");

            }
        }

        private void btn_BillSelect_Click(object sender, EventArgs e)
        {
            BillForm _frm_BillForm = new BillForm();
            _frm_BillForm.ShowDialog();
            if (_frm_BillForm.IsOk)
            {
                string pName = _frm_BillForm._pName;
                string pCode = _frm_BillForm._pCode;
                string pCnt = _frm_BillForm._planCnt;
                string billNo = _frm_BillForm._billNo;
                string manuCnt = _frm_BillForm._manuCnt;
                //billdate = frm._billdate;
                txt_BillNumber.Text = billNo;
                txt_ProductName.Text = pName;
                //_billNo = billNo;
                txt_ProductNumber.Text = pCode;
                txt_PlanOutput.Text = pCnt;
            }
            _frm_BillForm.Dispose();
        }

        private void btn_ProductionInfo_Click(object sender, EventArgs e)
        {
            ProductionInfoForm frm_ParameterForm = new ProductionInfoForm();
            frm_ParameterForm.ShowDialog();
        }

        private void btn_Debug_Click(object sender, EventArgs e)
        {
            DebugForm frm_ParameterForm = new DebugForm();
            frm_ParameterForm.ShowDialog();
        }

        private void btn_SetParameter_Click(object sender, EventArgs e)
        {
            string _BillNumber = txt_BillNumber.Text.Trim();
            if (_BillNumber.Length == 0)
            {
                MessageBox.Show("请选择工单");
                return;
            }

            try
            {
                string pwd = "";
                KeyBoardForm frm = new KeyBoardForm();
                frm.ShowDialog();
                if (frm.IsOk)
                {
                    pwd = frm.ReturnValue;
                }
                frm.Dispose();
                if (pwd.Length > 0)
                {
                    if (pwd == "111")
                    {
                        ParameterForm frm_ParameterForm = new ParameterForm();
                        frm_ParameterForm._frm_MainForm = this;
                        frm_ParameterForm.ShowDialog();
                        //frm_ParameterForm.Dispose();
                        //GetDeviceInfo();
                    }
                    else
                    {
                        MessageBox.Show("密码错误");
                    }
                }
            }
            catch
            {
            }
        }

        private void btn_AddBill_Click(object sender, EventArgs e)
        {
            try
            {
                string productName = txt_ProductName.Text.Trim();

                if (productName.Length == 0)
                {
                    MessageBox.Show("请选择产品");
                    return;
                }
                string productCode = txt_ProductNumber.Text.Trim();
                if (productCode.Length == 0)
                {
                    MessageBox.Show("请选择产品");
                    return;
                }
                if (txt_PlanOutput.Text.Trim().Length == 0)
                {
                    MessageBox.Show("请输入计划产量");
                    return;
                }
                string billNo = txt_BillNumber.Text.Trim();
                if (billNo.Length == 0)
                {
                    MessageBox.Show("请输入工单号");
                    return;
                }
                int plancnt = int.Parse(txt_PlanOutput.Text.Trim());
                if (plancnt == 0)
                {
                    MessageBox.Show("计划产量必须大于0");
                }
                else
                {

                    string sql = string.Format("INSERT  tb_bill(productname,productcode,billno,plancnt,inputdate,finished,inputtype,manucnt) values('{0}','{1}','{2}',{3},'{4}',0,1,0)", productName, productCode, billNo, plancnt, DateTime.Now.ToString("yyyyMMdd"));
                    if (SQLiteHelper.ExecuteNonQuery(sql) > 0)
                    {
                        MessageBox.Show("录入完成！");
                    }
                }
            }
            catch
            {
            }
        }

        private void btn_selectProduct_Click(object sender, EventArgs e)
        {
            ProductForm _frm_ProductForm = new ProductForm();
            _frm_ProductForm.ShowDialog();
            if (_frm_ProductForm.IsOk)
            {
                txt_ProductName.Text = _frm_ProductForm._pName;
                txt_ProductNumber.Text = _frm_ProductForm._pCode;
            }
            _frm_ProductForm.Dispose();
        }

        private void btn_setProNum_Click(object sender, EventArgs e)
        {
            try
            {
                KeyBoardForm _frm_KeyBoardForm = new KeyBoardForm();
                _frm_KeyBoardForm.ShowDialog();
                if (_frm_KeyBoardForm.IsOk)
                {
                    txt_PlanOutput.Text = _frm_KeyBoardForm.ReturnValue;
                }
                _frm_KeyBoardForm.Dispose();
            }
            catch
            {
            }
        }

        private void btn_setBillNum_Click(object sender, EventArgs e)
        {
            try
            {
                KeyBoardForm _frm_KeyBoardForm = new KeyBoardForm();
                _frm_KeyBoardForm.ShowDialog();
                if (_frm_KeyBoardForm.IsOk)
                {
                    txt_BillNumber.Text = _frm_KeyBoardForm.ReturnValue;
                }
                _frm_KeyBoardForm.Dispose();
            }
            catch
            {
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_FinishBill_Click(object sender, EventArgs e)
        {
            if (txt_BillNumber.Text.Trim().ToString() != "")
            {
                try
                {
                    if (MessageBox.Show("请确认工单是否生产完成？", "友情提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        string billNo = txt_BillNumber.Text.Trim();
                        if (billNo.Length > 0)
                        {
                            string sql = string.Format("update tb_bill set finished=1 where billno='{0}'", billNo);
                            if (SQLiteHelper.ExecuteNonQuery(sql) > 0)
                            {
                                MessageBox.Show("工单结束完毕！");
                            }
                            else
                            {
                                MessageBox.Show("不存在该工单");
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }

        private void btn_RunBill_Click(object sender, EventArgs e)
        {
            if (txt_BillNumber.Text == "")
            {
                MessageBox.Show("请选择工单");
                return;
            }



            #region 加载产品参数

            string strProductParam = "";
            Int64 ProductCheckSum = 0;

            int zongchang1=0;
            int zongchang2=0;
            int yuchuchang1=0;
            int yuchuchang2=0;
            int mansuchang=0;
            int jiasuchang = 0;
            int jiansuchang = 0;

            int songbu = 0;
            int chuanbu = 0;
            int xuanbu = 0;
            int raoxianman = 0;
            int raoxiankuai = 0;
            
            int shangjia1= 0;
            int ding1= 0;
            int xiaxi1= 0;
            int shangjia2= 0;
            int ding2= 0;
            int xiaxi2 =0;
            int shangda1= 0;
            int qie1= 0;
            int chu = 0;
            int shangda2=0;
            int qie2=0;                                       
   

            try
            {
                string sql = "SELECT * FROM tb_Length WHERE product_number = '" + txt_ProductNumber.Text.Trim() + "'";
                DataSet dsOne = SQLiteHelper.ExecuteDataset(sql);
                DataTable dtOne = dsOne.Tables[0];
                DataRow _tmp = dtOne.Rows[0];

                zongchang1 = Convert.ToInt32(_tmp["zongchang1"]);
                zongchang2 = Convert.ToInt32(_tmp["zongchang2"]);
                yuchuchang1 = Convert.ToInt32(_tmp["yuchuchang1"]);
                yuchuchang2 = Convert.ToInt32(_tmp["yuchuchang2"]);
                mansuchang = Convert.ToInt32(_tmp["mansuchang"]);
                jiasuchang = Convert.ToInt32(_tmp["jiasuchang"]);
                jiansuchang = Convert.ToInt32(_tmp["jiansuchang"]);
            }
            catch { }

            try
            {
                string sql = "SELECT * FROM tb_Speed WHERE product_number = '" + txt_ProductNumber.Text.Trim() + "'";
                DataSet dsOne = SQLiteHelper.ExecuteDataset(sql);
                DataTable dtOne = dsOne.Tables[0];
                DataRow _tmp = dtOne.Rows[0];

                songbu = Convert.ToInt32(_tmp["songbu"]);
                chuanbu = Convert.ToInt32(_tmp["chuanbu"]);
                xuanbu = Convert.ToInt32(_tmp["xuanbu"]);
                raoxianman = Convert.ToInt32(_tmp["raoxianman"]);
                raoxiankuai = Convert.ToInt32(_tmp["raoxiankuai"]);
            }
            catch { }

            try
            {
                string sql = "SELECT * FROM tb_Delay WHERE product_number = '" + txt_ProductNumber.Text.Trim() + "'";
                DataSet dsOne = SQLiteHelper.ExecuteDataset(sql);
                DataTable dtOne = dsOne.Tables[0];
                DataRow _tmp = dtOne.Rows[0];

                shangjia1 = Convert.ToInt32(_tmp["shangjia1"]);
                shangda1 = Convert.ToInt32(_tmp["shangda1"]);
                ding1 = Convert.ToInt32(_tmp["ding1"]);
                qie1 = Convert.ToInt32(_tmp["qie1"]);
                xiaxi1 = Convert.ToInt32(_tmp["xiaxi1"]);
                chu = Convert.ToInt32(_tmp["chu"]);
                shangjia2 = Convert.ToInt32(_tmp["shangjia2"]);
                shangda2 = Convert.ToInt32(_tmp["shangda2"]);
                ding2 = Convert.ToInt32(_tmp["ding2"]);
                qie2 = Convert.ToInt32(_tmp["qie2"]);
                xiaxi2 = Convert.ToInt32(_tmp["xiaxi2"]);
            }
            catch { }


            strProductParam = zongchang1.ToString() + "/" + zongchang2.ToString() + "/" + yuchuchang1.ToString() + "/" + yuchuchang1.ToString() + "/" + mansuchang.ToString() + "/" + jiasuchang.ToString() + "/" + jiansuchang.ToString() + "/" + 
                songbu.ToString() + "/" + chuanbu.ToString() + "/" + xuanbu.ToString() + "/" + raoxianman.ToString() + "/" + raoxiankuai.ToString() + "/" + 
                shangjia1.ToString() + "/" + shangda1.ToString() + "/" + ding1.ToString() + "/" + qie1.ToString() + "/" + xiaxi1.ToString() + "/" + chu.ToString() + "/" + shangjia2.ToString() + "/" +
                shangda2.ToString() + "/" + ding2.ToString() + "/" + qie2.ToString() + "/" + xiaxi2.ToString();

            ProductCheckSum = zongchang1 + zongchang2 + yuchuchang1 + yuchuchang1 + mansuchang + jiasuchang + jiansuchang +
                songbu + chuanbu + xuanbu + raoxianman + raoxiankuai +
                shangjia1 + shangda1 + ding1 + qie1 + xiaxi1 + chu + shangjia2 + shangda2 + ding2 + qie2 + xiaxi2;


            // 生成参数字符串
            string strParameter = "Loadvar#" + strProductParam + "/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/#" + Convert.ToString(ProductCheckSum) + "#";
            string[] sArrary = strParameter.Split('#');
            if (sArrary.Length < 3)
            {
            }
            else
            {
                string[] Arrary = sArrary[1].Split('/');

                for (int i = 0; i < 40; i++)
                {
                    if (Arrary[i] == null)
                    {
                        Data.var[i] = 0;
                    }
                    else
                    {
                        Data.var[i] = Convert.ToInt32(Arrary[i]);
                    }
                }
            }

            Data.Send(strParameter);
            #endregion

            System.Threading.Thread.Sleep(200);

            #region 加载机器参数

            // TODO
            string strMachineParam = "";
            Int64 MachineCheckSum = 0;

            int songzhoujia=0;
            int songzhoujian=0;
            int chuanzhoujia = 0;
            int chuanzhoujian=0;
            int xuanzhoujia=0;
            int xuanzhoujian=0;
            int raozhoujia=0;
            int raozhoujian=0;
            int fu1=0;
            int fu2=0;
            int xuan1=0;
            int xuan2=0;
            int nuanji_time=0;
            int bilichi1=0;
            int bilichi2=0;

            try
            {
                string sql = "SELECT * FROM tb_Parameter WHERE product_number = '" + txt_ProductNumber.Text.Trim() + "'";
                DataSet dsOne = SQLiteHelper.ExecuteDataset(sql);
                DataTable dtOne = dsOne.Tables[0];
                DataRow _tmp = dtOne.Rows[0];

                songzhoujia = Convert.ToInt32(_tmp["songzhoujia"]);
                songzhoujian = Convert.ToInt32(_tmp["songzhoujian"]);
                chuanzhoujia = Convert.ToInt32(_tmp["chuanzhoujia"]);
                chuanzhoujian = Convert.ToInt32(_tmp["chuanzhoujian"]);
                xuanzhoujia = Convert.ToInt32(_tmp["xuanzhoujia"]);
                xuanzhoujian = Convert.ToInt32(_tmp["xuanzhoujian"]);
                raozhoujia = Convert.ToInt32(_tmp["raozhoujia"]);
                raozhoujian = Convert.ToInt32(_tmp["raozhoujian"]);
                fu1 = Convert.ToInt32(_tmp["fu1"]);
                fu2 = Convert.ToInt32(_tmp["fu2"]);
                xuan1 = Convert.ToInt32(_tmp["xuan1"]);
                xuan2 = Convert.ToInt32(_tmp["xuan2"]);
                nuanji_time = Convert.ToInt32(_tmp["nuanji_time"]);
                bilichi1 = Convert.ToInt32(_tmp["bilichi1"]);
                bilichi2 = Convert.ToInt32(_tmp["bilichi2"]);

                
            }
            catch { }

            try
            {
                string sql = "SELECT * FROM tb_bilichi WHERE product_number = '" + txt_ProductNumber.Text.Trim() + "'";
                DataSet dsOne = SQLiteHelper.ExecuteDataset(sql);
                DataTable dtOne = dsOne.Tables[0];
                DataRow _tmp = dtOne.Rows[0];

                nuanji_time = Convert.ToInt32(_tmp["nuanji_time"]);
                bilichi1 = Convert.ToInt32(_tmp["bilichi1"]);
                bilichi2 = Convert.ToInt32(_tmp["bilichi2"]);
            }
            catch { }


            strMachineParam = songzhoujia.ToString() + "/" + songzhoujian.ToString() + "/" + chuanzhoujia.ToString() + "/" + chuanzhoujian.ToString() + "/" +
                    xuanzhoujia.ToString() + "/" + xuanzhoujian.ToString() + "/" + raozhoujia.ToString() + "/" + raozhoujian.ToString() + "/" + nuanji_time.ToString() + "/" +
                    bilichi1.ToString() + "/" + bilichi2.ToString();

            MachineCheckSum = songzhoujia + songzhoujian + chuanzhoujian + chuanzhoujian +
                xuanzhoujia + xuanzhoujian + raozhoujia + raozhoujian + nuanji_time +
                bilichi1 + bilichi2;


            string strParameter1 = "loadParameter#" + strMachineParam + "/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/#" + Convert.ToString(MachineCheckSum) + "#";

            // 生成参数字符串
            
            string[] sArrary1 = strParameter1.Split('#');

            Data.Send(strParameter1);

            string[] str1 = sArrary[1].Split('/');

            for (int i = 0; i < 40; i++)
            {
                if (str1[i] == null)
                {
                    Data.Parameter[i] = 0;
                }
                else
                {
                    Data.Parameter[i] = Convert.ToInt32(str1[i]);
                }

            }

            #endregion

            MessageBox.Show("数据加载完成！");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str1, str2 = "";

            if (Data.DataOutput[38] == 1)
            {
                btn_1shineng.BackColor = Color.Green;
            }
            else
            {
                btn_1shineng.BackColor = Color.White;
            }
            if (Data.DataOutput[39] == 1)
            {
                btn_2shineng.BackColor = Color.Green;
            }
            else
            {
                btn_2shineng.BackColor = Color.White;
            }
            if (Data.DataOutput[40] == 1)
            {
                btn_Step.BackColor = Color.Green;
            }
            else
            {
                btn_Step.BackColor = Color.White;
            }
            if (Data.DataOutput[41] == 1)
            {
                btn_last.BackColor = Color.Green;
            }
            else
            {
                btn_last.BackColor = Color.White;
            }

            str1 = "0000000000000000000000000000000000000000000000000000000000000000" + Convert.ToString(Data.DataInput_code, 2);
            if (str1.Length >= 60)
            {
                for (int i = 0; i < 60; i++)
                {
                    if (str1.Substring(str1.Length - i - 1, 1) == "0")
                    {
                        Data.DataInput[i] = 0;
                    }
                    else
                    {
                        Data.DataInput[i] = 1;

                    }

                }
            }
            str1 = "0000000000000000000000000000000000000000000000000000000000000000" + Convert.ToString(Data.DataOutput_code, 2);
            if (str1.Length >= 60)
            {
                for (int i = 0; i < 60; i++)
                {
                    if (str1.Substring(str1.Length - i - 1, 1) == "1")
                    {
                        Data.DataOutput[i] = 1;
                    }
                    else
                    {
                        Data.DataOutput[i] = 0;

                    }

                }
            }

            str1 = "00000000000000000000000000000000" + Convert.ToString(Data.error_code_num, 2);
            if (str1.Length >= 61)
            {
                for (int i = 0; i < 30; i++)
                {
                    if (str1.Substring(str1.Length - i - 1, 1) == "1")
                    {
                        Data.error_code[i] = true;
                    }
                    else
                    {
                        Data.error_code[i] = false;

                    }

                }

                if (Data.error_code[1]) { str2 = str2 + "\r\n" + "卡线报警！！！"; }
                if (Data.error_code[2]) { str2 = str2 + "\r\n" + "急停按下！！！"; }
                if (Data.error_code[3]) { str2 = str2 + "\r\n" + "机器复位未完成！！！"; }
                if (Data.error_code[4]) { str2 = str2 + "\r\n" + " 机器正在运行..."; }
                if (Data.error_code[5]) { str2 = str2 + "\r\n" + " 伺服报警！！！"; }
                if (Data.error_code[6]) { str2 = str2 + "\r\n" + " 伺服报警！！！"; }
                if (Data.error_code[7]) { str2 = str2 + "\r\n" + " 伺服报警！！！"; }
                if (Data.error_code[8]) { str2 = str2 + "\r\n" + " 伺服报警！！！"; }
                if (Data.error_code[9]) { str2 = str2 + "\r\n" + " 请加载程序！！！"; }
                if (Data.error_code[10]) { str2 = str2 + "\r\n" + " 复位超时！！！"; }
                if (Data.error_code[11]) { str2 = str2 + "\r\n" + " 运行超时！！！"; }

                //  if (Data.error_code[12]) { str2 = str2 + "\r\n" + " 导针气缸未动到位！！！"; }
                //  if (Data.error_code[13]) { str2 = str2 + "\r\n" + " 导针气缸未回到位！！！"; }
                //  if (Data.error_code[14]) { str2 = str2 + "\r\n" + " 上磁芯缸未动到位！！！"; }
            }
            else
            {
                { str2 = str2 + "\r\n" + "机器通讯异常,请检查主机是否开启！"; }

            }

            label4.Text = "现在的圈数: " + Convert.ToString(Data.now_rounds) + "\r\n" + str2;

            //textBox1.Text = Convert.ToString(Data.progrm_name);

            lab_time.Text = DateTime.Now.ToString(); 
        }
    }
}